<?php

namespace App\Services;

use App\Exceptions\InternalException;
use App\Exceptions\InvalidRequestException;
use App\Models\ConstructionDiary;
use Illuminate\Support\Facades\Log;

class ConstructionDiaryService
{
    public function get($type){
        $sql = ConstructionDiary::where('id','>',0);
        return $sql;
    }

    public function insert($input){
        $res = [];
        foreach ($input as $k => $v) {
            if($v){
                $res[$k] = $v;
            }
        }
        try {
            $data = ConstructionDiary::create($res);
            if($data){
                return $data;
            }
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }

    public function update($input){


        $data = ConstructionDiary::with('application')->where('id',$input['id'])->first();
        if($data->application){
            if($data->application->status == 'pending'){
                throw new InvalidRequestException('正在审批中，无法修改');
            }
            if($data->application->status == 'approved'){
                throw new InvalidRequestException('已经审核通过，无法修改');
            }
        }
        //判断审批是否通过
        foreach ($input as $k => $v) {
            $data->$k = $v;
        }
        try {
            $data->save();
            return $data;
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }
}